package cn.ryh.hystrixproviderpayone.discovery.controller;

import cn.ryh.apicommons.entities.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName DiscoveryController
 * @Description TODO
 * @Author RaoYH
 * @CreateDate 2020/12/7
 * @UpdateUser RaoYH
 * @UpdateDate 2020/12/7
 * @UpdateRemark TODO
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/discovery")
public class DiscoveryController {
    private static final Logger log = LoggerFactory.getLogger(DiscoveryController.class);
    @Value("${server.port}")
    private String port;
    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 获取所有的注册信息
     */
    @GetMapping(value = "/getServers")
    public CommonResult getServers() {
        List<String> services = discoveryClient.getServices();
        for (String s : services) {
            log.info("》》》》》service:" + s);
        }
        if (services != null) {
            return new CommonResult<>(200, "查询Servers成功,port:" + port, services);
        } else {
            return new CommonResult<>(444, "没有对应Servers记录");
        }
    }

    /**
     * 获取指定服务名称的所有服务注册信息
     */
    @GetMapping(value = "/getInstances/{serviceId}")
    public CommonResult getInstances(@PathVariable("serviceId") String serviceId) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        for (ServiceInstance instance : instances) {
            log.info("》》》》》instance:" + instance.getInstanceId() + "\t" + instance.getHost() + "\t"
                    + instance.getPort() + "\t" + instance.getUri());
        }
        if (instances != null) {
            return new CommonResult<>(200, "查询Servers成功,port:" + port, instances);
        } else {
            return new CommonResult<>(444, "没有对应Servers记录");
        }
    }
}
